package com.zxmc.task;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import com.zxmc.server.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Component;

@Component
public class UserSessionManager {
    private final Map<Integer, ScheduledFuture<?>> userTasks = new HashMap<>();
    private final ScheduledExecutorService scheduler = java.util.concurrent.Executors.newScheduledThreadPool(10);

    @Autowired
    private RecommendationService recommendationService;
    @CacheEvict(value = "recommendCache",beforeInvocation = true)
    // 用户登录时启动定时任务
    public void startTaskForUser(int userId) {
        if(userTasks.containsKey(userId)) {
            return;
        }
        ScheduledFuture<?> task = scheduler.scheduleAtFixedRate(() -> {
            // 执行定时任务逻辑，例如更新推荐信息
            System.out.println("为用户 " + userId + " 执行定时任务");
            recommendationService.callRecommandFun(userId);
        }, 5, 10, TimeUnit.MINUTES);
        userTasks.put(userId, task);
    }

    // 用户注销时停止定时任务
    public void stopTaskForUser(int userId) {
        ScheduledFuture<?> task = userTasks.get(userId);
        if (task != null) {
            task.cancel(true);
            userTasks.remove(userId);
        }
    }
}